import React, { useEffect } from 'react';

// https://zh-hans.reactjs.org/docs/forwarding-refs.html#forwarding-refs-in-higher-order-components
function logProps(WrappedComponent: any) {
  class LogProps extends React.Component<any> {
    componentDidUpdate(prevProps: any) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }

  return LogProps;
}

function logProps1(Component: any) {
  class LogProps extends React.Component<any> {
    componentDidUpdate(prevProps: any) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

    render() {
      const { forwardedRef, ...rest } = this.props;
      // 将自定义的 prop 属性 “forwardedRef” 定义为 ref
      return <Component ref={forwardedRef} {...rest} />;
    }
  }
  return React.forwardRef((props: any, ref) => {
    return <LogProps {...props} forwardedRef={ref} />;
  });
}

class FancyButton extends React.Component<any> {
  focus() {
    console.log('focus');
  }
  render(): React.ReactNode {
    return <div>FancyButton</div>;
  }
}

const FancyButton1 = logProps(FancyButton);

const FancyButton2 = logProps1(FancyButton);

export default function ForwardRefHoc() {
  const ref1: React.LegacyRef<any> | undefined = React.createRef();
  const ref2 = React.createRef();
  useEffect(() => {
    // ref1 {current: LogProps}
    console.log('ref1', ref1);
    // ref2 {current: FancyButton}
    console.log('ref2', ref2);
  }, []);
  return (
    <div>
      <FancyButton1 ref={ref1} />
      <FancyButton2 ref={ref2} />
    </div>
  );
}
